package 设计模式.创建者模式.单例模式.懒汉式_双重检查锁;

/**
 * @Author: kirito
 * @Date: 2024/3/8 11:08
 * @Description:
 */

public class Singleton {
    // 私有构造方法，防止外部实例化
    private Singleton() {}
    //这里要加volatile  确保多线程环境下的可见性和禁止指令重排序
    private static volatile Singleton instance;

    public static Singleton getInstance() {
        //兼顾性能，避免每次都加锁
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
